package jsu.blogger.util;

import jakarta.servlet.http.HttpServletRequest;
import jsu.blogger.controller.LiveController;
import jsu.blogger.pojo.Result;
import jsu.blogger.service.impl.GetUserDataServiceImpl;
import lombok.experimental.UtilityClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;

import java.io.File;
import java.io.IOException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
public class UserUtil {
    @Value("${dir.userAvatarDir}")
    private static String userAvatarDir;
    private static final Logger log = LoggerFactory.getLogger(UserUtil.class);
    public static Map<String,Object> getUserAvatar(Long userId) {
        String userAvatarFileNamePrefix = "userAvatar" + userId;
        Path userAvatarDirectory = Paths.get(userAvatarDir);
        File userAvatar=null;
        Map<String,Object> reMap=new HashMap<>();
        // 确保目录存在
        try{
            if (!Files.exists(userAvatarDirectory) || !Files.isDirectory(userAvatarDirectory)) {
                return null; // 目录不存在，返回 null
            }

            // 使用 DirectoryStream 遍历文件
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(userAvatarDirectory,
                    path -> path.getFileName().toString().startsWith(userAvatarFileNamePrefix))) {
                for (Path path : directoryStream) {
                    userAvatar=path.toFile();
                    break;
                }
            } catch (IOException e) {
                log.error(String.valueOf(e));
            }

            if(userAvatar!=null){
                try{
                    String imgType="data:image/"+getFileExtension(userAvatar)+";";
                    // 将文件内容读取为字节数组
                    byte[] fileContent = Files.readAllBytes(userAvatar.toPath());
                    // 将字节数组编码为 Base64 字符串
                    String base64String = Base64.getEncoder().encodeToString(fileContent);

                    reMap.put("imgType",imgType);
                    reMap.put("userAvatar",base64String);
                } catch (IOException e) {
                    log.error(String.valueOf(e));
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return reMap;
    }
    private static String getFileExtension(File file) {
        // 确保传入的是有效的文件对象
        if (file == null || !file.exists()) {
            throw new IllegalArgumentException("文件不存在或无效");
        }
        // 获取文件名
        String fileName = file.getName();

        // 找到最后一个点的位置
        int lastDotIndex = fileName.lastIndexOf('.');

        // 如果没有点，返回空字符串
        if (lastDotIndex == -1) {
            return "";
        }
        // 提取后缀名并转换为小写
        return fileName.substring(lastDotIndex + 1).toLowerCase();
    }
}
